<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="100px">

      <el-form-item label="课题名称" prop="projectName">
        <el-input
            v-model="queryParams.projectName"
            placeholder="请输入课题名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课题级别" prop="projectLevel">
        <el-select v-model="queryParams.projectLevel" placeholder="请选择课题级别" clearable>
           <el-option label="国家级" value="国家级" />
           <el-option label="省部级" value="省部级" />
           <el-option label="市厅级" value="市厅级" />
          <el-option label="其它" value="其它" />
        </el-select>
     </el-form-item>
      <el-form-item label="课题状态" prop="projectStatus">
        <el-select v-model="queryParams.projectStatus" placeholder="请选择课题状态" clearable>
          <el-option label="在研" value="在研" />
          <el-option label="结题" value="结题" />
        </el-select>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['result:longitudinalProjects:export']"
        >导出</el-button>
      </el-form-item>
    </el-form>



    <el-table v-loading="loading" :data="longitudinalProjectsList" @selection-change="handleSelectionChange" ref="longitudinalTable">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="主键，自增" align="center" prop="id" />-->
      <el-table-column label="上传者" align="center" prop="nickName" />
      <el-table-column label="课题名称" align="center" prop="projectName" />
      <el-table-column label="课题类型" align="center" prop="projectType" />
      <el-table-column label="授予单位" align="center" prop="grantingUnit" />
      <el-table-column label="课题级别" align="center" prop="projectLevel" />
      <el-table-column label="本人排名" align="center" prop="rank" />
      <el-table-column label="课题状态" align="center" prop="projectStatus" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="240">
        <template #default="scope">
          <el-button
              link
              type="primary"
              icon="Download"
              @click="download(scope.row)"
              :disabled="!scope.row.pdfUrl"
          >下载</el-button>
          <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['result:longitudinalProjects:edit']"
          >详情</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />


    <longitudinal-export v-model="showExportDialog" :longitudinals="exportData" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { treeselect } from "@/api/system/dept";
import LongitudinalExport from "@/components/result/ExportDialog/longitudinalExport.vue";
import { listLongitudinalProjects, getLongitudinalProjects, delLongitudinalProjects, addLongitudinalProjects, updateLongitudinalProjects,getLongitudinalsByIds } from "@/api/result/longitudinalProjects"
import {listPostOptions} from "../../../api/system/post";
import {getRoleOptions} from "../../../api/system/role";
import {useRoute, useRouter} from "vue-router";

const router = useRouter()
const route = useRoute()
const queryFormRef = ref(null)
const formRef = ref(null)
const loading = ref(false)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const open = ref(false)
const longitudinalProjectsList = ref([])
const deptName = ref("");
const deptOptions = ref(undefined);
const postOptions = ref([]);
const roleOptions = ref([]);
const longitudinalTable = ref(null);
const exportData = ref([]);
const showExportDialog = ref(false);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  projectName: null,
  fundName: null,
  projectType: null,
  grantingUnit: null,
  projectLevel: null,
  projectNumber: null,
  fundingAmount: null,
  rank: null,
  startTime: null,
  endTime: null,
  authorInfo: null,
  projectStatus: null,
  remarks: null,
  pdfUrl: null,
  syncStatus: null,
  createdAt: null,
  updatedAt: null,
  userId: null,
  queryPublishDate: [],
  deptId: null,
  postIds: [],
  roleIds: [],
})

const form = reactive({
  id: null,
  projectName: null,
  fundName: null,
  projectType: null,
  grantingUnit: null,
  projectLevel: null,
  projectNumber: null,
  fundingAmount: null,
  rank: null,
  startTime: null,
  endTime: null,
  authorInfo: null,
  projectStatus: "0",
  remarks: null,
  pdfUrl: null,
  syncStatus: "0",
  createdAt: null,
  updatedAt: null,
  userId: null,
  postIds: [],
  roleIds: [],
})


const download = (row) => {
  if (row.pdfUrl) {
    console.log('下载:', row.pdfUrl);
    window.open(row.pdfUrl, '_blank');
  } else {
    ElMessage.warning('该报告没有可下载的PDF文件');
  }
};
onMounted(() => {

  getList()
})
/** 查询系部下拉树结构 */
function getDeptTree() {
  treeselect().then(response => {
    deptOptions.value = response.data;
  });
  // deptTreeSelect().then(response => {
  //   deptOptions.value = response.data;
  // });
};
/** 查询纵向课题列表 */
function getList() {
  loading.value = true
  listLongitudinalProjects(queryParams).then(response => {
    longitudinalProjectsList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.id = null
  form.projectName = null
  form.fundName = null
  form.projectType = null
  form.grantingUnit = null
  form.projectLevel = null
  form.projectNumber = null
  form.fundingAmount = null
  form.rank = null
  form.startTime = null
  form.endTime = null
  form.authorInfo = null
  form.projectStatus = "0"

  form.remarks = null
  form.pdfUrl = null
  form.syncStatus = "0"
  form.createdAt = null
  form.updatedAt = null
  form.userId = null
  formRef.value?.resetFields()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields()
  queryParams.postIds = [];
  queryParams.roleIds = [];
  queryParams.queryPublishDate = [];
  handleQuery()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加纵向课题"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  console.log('编辑:', row.id);
  router.push({ path: '/result/longitudinal/edit', query: { id: row.id } });
  // reset()
  // const id = row.id || ids.value
  // getLongitudinalProjects(id).then(response => {
  //   Object.assign(form, response.data)
  //   open.value = true
  //   title.value = "修改纵向课题"
  // })
}

/** 提交按钮 */
function submitForm() {
  formRef.value?.validate(valid => {
    if (valid) {
      if (form.id != null) {
        updateLongitudinalProjects(form).then(response => {
          ElMessage.success("修改成功")
          open.value = false
          getList()
        })
      } else {
        addLongitudinalProjects(form).then(response => {
          ElMessage.success("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}



/** 导出按钮操作 */
async function handleExport() {
  const selectedRows = longitudinalTable.value.getSelectionRows();
  if (selectedRows.length === 0) {
    ElMessage.warning('请选择要导出的纵向课题');
    return;
  }

  // 提取选中纵向课题的 id
  const selectedIds = selectedRows.map(item => item.id);

  // 这里需要实现获取选中纵向课题详细信息的 API
  const res = await getLongitudinalsByIds(selectedIds);
  console.log('导出:', res);
  if (res.code === 200 && res.data) {
    showExportDialog.value = true;
    exportData.value = res.data;
  } else {
    ElMessage.error('获取纵向课题数据失败');
  }

  // 临时使用选中的行数据
  showExportDialog.value = true;
  exportData.value = selectedRows;
}

</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>
